package com.smedi.ismedi.web.starter.config;

import com.smedi.ismedi.web.starter.util.BaseUtil;
import com.smedi.ismedi.web.starter.util.DozerUtil;
import com.smedi.ismedi.web.starter.util.PinyinUtil;
import com.smedi.ismedi.web.starter.util.SegmentateUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan({
        "com.smedi.ismedi.web.starter.property",
        "com.smedi.ismedi.web.starter.handler",
        "com.smedi.ismedi.web.starter.async"
})
@ConditionalOnClass({
        BaseUtil.class, PinyinUtil.class, SegmentateUtil.class, DozerUtil.class
})
@Slf4j
public class WebAutoConfig {
    /**
     * 自动装载
     *
     * @param clz
     * @param <T>
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    private <T> T assemble(Class<T> clz) throws InstantiationException, IllegalAccessException {
        log.info("装配：{}", clz.getName());
        return clz.newInstance();
    }

    @SneakyThrows({InstantiationException.class, IllegalAccessException.class})
    @Bean
    @ConditionalOnMissingBean(BaseUtil.class)
    public BaseUtil baseUtil() {
        return assemble(BaseUtil.class);
    }

    @SneakyThrows({InstantiationException.class, IllegalAccessException.class})
    @Bean
    @ConditionalOnMissingBean(DozerUtil.class)
    public DozerUtil dozerUtil() {
        return assemble(DozerUtil.class);
    }

    @SneakyThrows({InstantiationException.class, IllegalAccessException.class})
    @Bean
    @ConditionalOnMissingBean(PinyinUtil.class)
    public PinyinUtil pingyinUtil() {
        return assemble(PinyinUtil.class);
    }

    @SneakyThrows({InstantiationException.class, IllegalAccessException.class})
    @Bean
    @ConditionalOnMissingBean(SegmentateUtil.class)
    public SegmentateUtil segmentateUtil() {
        return assemble(SegmentateUtil.class);
    }
}